package com.wallet.crypto.trustapp.util;

import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;

/**
 * 仅限单线程
 */
public class KeyboardCover {

    private static int sInt;
    public static int scrollToPosition = 0;
    private static View[] roots = new View[3];
    private static ViewTreeObserver.OnGlobalLayoutListener[] listeners = new ViewTreeObserver.OnGlobalLayoutListener[3];

    public static void removeGlobalLayoutListener() {
        if (roots == null)
            return;
        if (listeners == null)
            return;
        for (int i = 0; i < roots.length; i++) {
            roots[i].getViewTreeObserver().removeOnGlobalLayoutListener(listeners[i]);
        }
        roots = null;
        listeners = null;
        sInt = 0;
    }

    /**
     * 键盘遮挡控件
     * ⚠️注意：
     * 每个页面用完后 KeyboardCover.scrollToPosition=0;
     * 最后不使用了，要 removeGlobalLayoutListener();
     */
    public static void autoScrollView(final View root, final View scrollToView) {

        ViewTreeObserver.OnGlobalLayoutListener listener = () -> {
            Rect rect = new Rect();

            //获取root在窗体的可视区域
            root.getWindowVisibleDisplayFrame(rect);

            //获取root被遮挡的高度
            View rootView = root.getRootView();
            int rootInvisibleHeight = rootView.getHeight() - rect.bottom;

            if (rootInvisibleHeight > 200) {
                if (scrollToPosition != 0) {
                    return;
                }
                //获取scrollToView在窗体的坐标,location[0]为x坐标，location[1]为y坐标
                int[] location = new int[2];
                scrollToView.getLocationInWindow(location);
                int scrollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
                scrollToPosition += scrollHeight;
            } else {
                scrollToPosition = 0;
            }
            root.scrollTo(0, scrollToPosition);
        };
        root.getViewTreeObserver().addOnGlobalLayoutListener(listener);

        int i = sInt++;
        listeners[i] = listener;
        roots[i] = root;
    }
}
